<template>
  <!-- 校区签约统计模块 -->
  <el-card class="data-card" shadow="never">
    <div slot="header" class="card-header">
      <div class="header-left">
        <i class="el-icon-s-cooperation" />
        <span>新加盟统计(按签约日期)</span>
      </div>
      <div class="header-right">
        <el-select v-model="filterForm.brand" placeholder="请选择品牌" size="small" style="width: 120px; margin-right: 8px;" @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option v-for="item in brandOptions" :key="item.enCode" :label="item.fullName" :value="item.enCode" />
        </el-select>
        <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" size="small" style="width: 220px; margin-right: 8px;" @change="handleFilterChange" />

        <el-button size="small" icon="el-icon-refresh" :loading="loading" @click="refreshData">刷新</el-button>
      </div>
    </div>
    <div v-loading="loading" class="table-container">
      <!-- 签约透视表格：管理区域为列，月度为行 -->
      <el-table :data="pivotData" size="small" stripe border show-summary :summary-method="getPivotSummaries" sum-text="总计" class="report-table optimized-table">
        <el-table-column prop="month" label="月份" min-width="120" align="center">
          <template slot-scope="scope">
            <span class="data-primary">{{ scope.row.month }}</span>
          </template>
        </el-table-column>
        <el-table-column v-for="area in areas" :key="area.code" :prop="'area_' + area.code" :label="area.name" min-width="100" align="center">
          <template slot-scope="scope">
            <span class="data-success">{{ scope.row['area_' + area.code] || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="总计" min-width="90" align="center">
          <template slot-scope="scope">
            <span class="data-info">{{ scope.row.total }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-card>
</template>

<script>
import { getCampusContractStatistics } from '@/api/report/branch'
import { mockContractData } from '@/mock/contractData'

export default {
  name: 'ContractStatisticsReport',
  props: {
    // 管理区域选项
    managementAreaOptions: {
      type: Array,
      default: () => []
    },
    // 品牌选项
    brandOptions: {
      type: Array,
      default: () => []
    },
    // 初始筛选条件
    initialFilter: {
      type: Object,
      default: () => ({
        brand: '',
        dateRange: []
      })
    }
  },
  data() {
    // 获取当前年度时间范围
    const getCurrentYearRange = () => {
      const currentYear = new Date().getFullYear()
      const startDate = `${currentYear}-01-01`
      const endDate = `${currentYear}-12-31`
      return [startDate, endDate]
    }

    return {
      loading: false,
      contractData: [],
      pivotData: [],
      areas: [],

      filterForm: {
        brand: '',
        dateRange: getCurrentYearRange()
      }
    }
  },
  watch: {
    initialFilter: {
      handler(newVal) {
        if (newVal) {
          // 合并初始筛选条件，但保持默认的本年度日期范围
          this.filterForm = {
            ...this.filterForm,
            ...newVal,
            // 如果initialFilter没有设置dateRange或为空，保持默认的本年度范围
            dateRange: newVal.dateRange && newVal.dateRange.length > 0 ? newVal.dateRange : this.filterForm.dateRange
          }
          this.loadContractData()
        }
      },
      immediate: true,
      deep: true
    },

    managementAreaOptions: {
      handler() {
        if (this.managementAreaOptions.length > 0) {
          this.loadContractData()
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.loadContractData()
  },
  methods: {
    // 加载签约统计数据
    async loadContractData() {
      this.loading = true

      try {
        // 构建查询参数
        const params = {}

        // 添加品牌筛选参数
        if (this.filterForm.brand && this.filterForm.brand !== '') {
          params.brand = this.filterForm.brand
        }

        // 添加时间范围参数
        if (this.filterForm.dateRange && this.filterForm.dateRange.length === 2) {
          params.startDate = this.filterForm.dateRange[0]
          params.endDate = this.filterForm.dateRange[1]
        }

        let contractResponse
        try {
          // 调用签约统计接口
          contractResponse = await getCampusContractStatistics(params)
        } catch (apiError) {
          console.warn('API调用失败，使用模拟数据:', apiError)
          // 如果API调用失败，使用模拟数据
          contractResponse = mockContractData
        }

        // 处理签约数据 - 根据后端返回的数据结构进行调整
        let responseData = contractResponse.data || contractResponse
        if (responseData && responseData.data && responseData.data.monthlyStatistics) {
          // 如果返回的是包装格式，提取monthlyStatistics
          responseData = responseData.data.monthlyStatistics
        } else if (responseData && responseData.monthlyStatistics) {
          // 如果直接包含monthlyStatistics
          responseData = responseData.monthlyStatistics
        }

        this.contractData = this.processContractData(responseData)

        // 生成签约透视表数据
        this.generateContractPivotData()

        // 计算招商签约指标并通知父组件数据已更新
        this.calculateContractMetrics()

        this.$emit('data-updated', {
          contractData: this.contractData,
          pivotData: this.pivotData,
          areas: this.areas
        })
      } catch (error) {
        this.$message.error('签约统计数据加载失败')
        console.error('签约统计数据加载错误:', error)

        // 如果API调用失败，初始化空数据
        this.contractData = []
        this.pivotData = []
        this.areas = []
      } finally {
        this.loading = false
      }
    },

    // 处理签约数据
    processContractData(data) {
      if (!data || !Array.isArray(data)) {
        // 签约数据格式错误
        return []
      }
      return data.map(item => ({
        ...item,
        // 构建月份标识，用于分组
        month: `${item.year}-${String(item.month).padStart(2, '0')}`,
        monthDisplay: this.formatMonth(`${item.year}-${String(item.month).padStart(2, '0')}`),
        regionName: this.getRegionName(item.managementArea)
      }))
    },

    // 生成签约透视表数据
    generateContractPivotData() {
      if (!this.contractData || this.contractData.length === 0) {
        this.pivotData = []
        this.areas = []
        return
      }

      // 获取所有唯一的月份和管理区域
      const months = [...new Set(this.contractData.map(item => item.month))].sort()
      const regions = [...new Set(this.contractData.map(item => item.managementArea))]

      // 构建区域列表
      this.areas = regions.map(regionCode => {
        return {
          code: regionCode,
          name: this.getRegionName(regionCode),
          sortCode: this.getRegionSort(regionCode)
        }
      })

      // 构建透视表数据
      this.pivotData = months.map(month => {
        const row = {
          month: this.formatMonth(month),
          total: 0
        }

        // 为每个区域添加数据
        this.areas.forEach(area => {
          const areaData = this.contractData.find(item => item.month === month && item.managementArea === area.code)
          const count = areaData ? areaData.contractCount : 0
          row[`area_${area.code}`] = count
          row.total += count
        })

        return row
      })
    },

    // 格式化月份显示
    formatMonth(month) {
      if (!month) return ''
      if (typeof month === 'string' && month.includes('-')) {
        const [year, monthNum] = month.split('-')
        return `${year}年${monthNum}月`
      }
      return month
    },

    // 获取区域名称
    getRegionName(regionCode) {
      const region = this.managementAreaOptions.find(item => item.enCode === regionCode)
      return region ? region.fullName : regionCode
    },

    // 获取区域排序值
    getRegionSort(regionCode) {
      const region = this.managementAreaOptions.find(item => item.enCode === regionCode)
      const sortCode = region ? region.sortCode || 999 : 999
      // 强制转换为数字类型
      const numericSortCode = Number(sortCode)
      // 强制转换为数字类型
      return isNaN(numericSortCode) ? 999 : numericSortCode
    },

    // 获取透视表汇总
    getPivotSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = 'N/A'
        }
      })
      return sums
    },

    // 计算招商签约指标
    calculateContractMetrics() {
      // 计算招商签约总数（使用模拟数据，与原逻辑保持一致）
      const totalInvestment = 156 + Math.floor(Math.random() * 50) // 模拟数据：150-200之间

      // 模拟增长率（-15% 到 +15%）
      const investmentGrowthRate = Math.floor(Math.random() * 30) - 15

      // 通过事件发送指标数据给父组件
      this.$emit('metrics-updated', {
        totalInvestment,
        investmentGrowthRate
      })
    },

    // 处理筛选条件变化
    handleFilterChange() {
      this.loadContractData()
      this.$emit('filter-change', this.filterForm)
    },

    // 刷新数据
    refreshData() {
      this.loadContractData()
      this.$emit('refresh')
    }
  }
}
</script>

<style scoped>
@import './shared-table-styles.scss';
</style>
